/**
 * Copyright © 2019 dream horse Info. Tech Ltd. All rights reserved.
 *
 * @Package: com.gitee.mybatis.fl.convert
 * @author: flying-cattle
 * @date: 2019年4月9日 下午8:15:25
 */
package com.fdy.code.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import cn.hutool.core.util.StrUtil;
import com.fdy.code.entity.BasisInfo;
import com.fdy.code.entity.ConfigObj;
import com.fdy.code.entity.ResultJson;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * Copyright: Copyright (c) 2019 
 *
 * <p>说明：  创建文件</P>
 * @version: v3.0.0
 * @author: flying-cattle
 *
 * Modification History:
 * Date         	Author          Version          Description
 *---------------------------------------------------------------*
 * 2019年4月9日      		flying-cattle   v3.0.0           initialize
 */
public class FreemarkerUtil {
    private static final Logger logger = LogManager.getLogger(FreemarkerUtil.class);

    public static ResultJson createFile(BasisInfo dataModel, String templateName, String filePath) {
        ResultJson result = new ResultJson();
        FileWriter out = null;
        String fileName = dataModel.getEntityName() + messageStr(templateName);
        try {
            // 通过FreeMarker的Confuguration读取相应的模板文件
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            ConfigObj configObj = dataModel.getConfigObj();
            // 设置模板路径
            if (StrUtil.isNotEmpty(configObj.getTemplateType())) {
                configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/freemarker/ftl/"
                        + configObj.getTemplateType()+"/");
            } else {
                configuration.setClassForTemplateLoading(FreemarkerUtil.class, "/freemarker/ftl");
            }

            // 设置默认字体
            configuration.setDefaultEncoding("utf-8");
            // 获取模板
            Template template = configuration.getTemplate(templateName);
            File file = new File(filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            } else {
                result.setCode(-1);
                result.setMessage("已经存在" + fileName);
                return result;
            }

            //设置输出流
            out = new FileWriter(file);
            //模板输出静态文件
            template.process(dataModel, out);
            result.setCode(1);
            result.setMessage("创建" + fileName + "成功");
            logger.info("创建文件结果{}", result);
            return result;
        } catch (Exception e) {
            logger.error("失败", e);
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error("IOException失败", e);
                }
            }
        }
        result.setCode(-1);
        result.setMessage("创建" + fileName + "失败");
        logger.info("创建文件结果{}", result);
        return result;
    }

    public static String messageStr(String name) {
        if (name.equals("entity.ftl")) {
            name = ".java";
        } else if (name.equals("dao.ftl")) {
            name = "Dao.java";
        } else if (name.equals("mapper.ftl")) {
            name = "Mapper.xml";
        } else if (name.equals("service.ftl")) {
            name = "Service.java";
        } else if (name.equals("serviceImpl.ftl")) {
            name = "ServiceImpl.java";
        } else if (name.equals("controller.ftl")) {
            name = "Controller.java";
        }
        return name;
    }
}
